package com.bird.framework.security.service;

import cn.hutool.core.util.ObjectUtil;
import com.bird.common.constant.Coder;
import com.bird.common.exception.CustomException;
import com.bird.system.domain.bo.LoginUser;
import com.bird.system.domain.entity.SysUserEntity;
import com.bird.system.enums.UserStatus;
import com.bird.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author bird
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private ISysUserService userService;

	@Autowired
	private SysPermissionService permissionService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUserEntity user = userService.selectUserByUserName(username);
		if (ObjectUtil.isNull(user)) {
			log.info("登录用户：{} 不存在.", username);
			throw new UsernameNotFoundException(username);
		} else if (UserStatus.DELETED.getKey().equals(user.getDelFlag())) {
			log.info("登录用户：{} 已被删除.", username);
			throw new CustomException(Coder.SysUser.ACCOUNT_DELETION.build(username));
		} else if (UserStatus.DISABLE.getKey().equals(user.getStatus())) {
			log.info("登录用户：{} 已被停用.", username);
			throw new CustomException(Coder.SysUser.ACCOUNT_DEACTIVATION.build(username));
		}

		return createLoginUser(user);
	}

	public UserDetails createLoginUser(SysUserEntity user) {
		return LoginUser.buildSystemUser(user, permissionService.getMenuPermission(user));
	}
}
